<template>
  <div class="idcard-verification">
    <div class="verification-container">
      <h2 class="page-title">身份证实名认证</h2>
      
      <!-- 上传区域 -->
      <div class="upload-section">
        <div class="upload-area" @click="triggerUpload" v-if="!imgurl">
          <div class="upload-icon">
            <el-icon><Upload /></el-icon>
          </div>
          <div class="upload-text">
            点击上传身份证照片
          </div>
          <div class="upload-tip">
            支持 JPG、PNG 格式，文件大小不超过 5MB
          </div>
        </div>
        
        <!-- 隐藏的文件输入 -->
        <input
          ref="fileInput"
          type="file"
          accept=".jpg,.jpeg,.png"
          style="display: none"
          @change="handleFileChange"
        />
        
                 <!-- 图片预览 -->
         <div v-if="imgurl" class="image-preview">
           <img 
             :src="imgurl" 
             alt="身份证预览" 
             class="preview-image" 
             @error="handleImageError"
             @load="handleImageLoad"
           />
           <div class="image-actions">
             <el-button size="small" @click="reupload">重新上传</el-button>
           </div>
         </div>
      </div>

      <!-- 识别结果 -->
      <div v-if="name || idcode" class="result-section">
        <h3>识别结果</h3>
        <div class="form-group">
          <label>真实姓名：</label>
          <el-input v-model="name" placeholder="真实姓名" />
        </div>
        <div class="form-group">
          <label>身份证号：</label>
          <el-input v-model="idcode" placeholder="身份证号" />
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="recognizeIdCard" :loading="recognizing">
            重新识别
          </el-button>
          <el-button type="success" @click="submitVerification" :loading="submitting">
            提交认证
          </el-button>
        </div>
      </div>

             <!-- 加载状态 -->
       <div v-if="recognizing" class="loading-section">
         <div class="loading-spinner"></div>
         <p>{{ processingStatus || '正在识别身份证信息...' }}</p>
       </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { authAPI } from '@/api/index'

export default {
  name: 'IdCardVerificationView',
  setup() {
    const router = useRouter()
    const token = ref('')
    const imgurl = ref('')
    const name = ref('')
    const idcode = ref('')
    const recognizing = ref(false)
    const submitting = ref(false)
    const fileInput = ref(null)
    const checkInterval = ref(null) // 添加定时器引用
    const processingStatus = ref('') // 添加处理状态
    
    // 备用域名列表（已简化，不再需要）
    const backupDomains = ref([])
    const currentDomainIndex = ref(0)

    // 获取七牛云token
    const getQiniuToken = async () => {
  try {
    const response = await authAPI.getIdCardQiniuToken()
        console.log('七牛云token响应:', response) // 调试信息
        
        // 直接使用axios时，response是完整的axios响应对象
        // 需要从response.data中获取实际数据
        if (response && response.data && response.data.code === 200 && response.data.data) {
          token.value = response.data.data
          console.log('获取七牛云token成功:', token.value)
          ElMessage.success('获取上传token成功')
        } else {
          console.error('响应格式错误:', response)
          ElMessage.error('获取上传token失败')
        }
      } catch (error) {
        console.error('获取七牛云token失败:', error)
        ElMessage.error('获取上传token失败')
      }
    }

    // 触发文件选择
    const triggerUpload = () => {
      fileInput.value.click()
    }

    // 处理文件选择
    const handleFileChange = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      console.log('选择的文件:', file) // 调试信息

      // 验证文件类型和大小
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
      if (!allowedTypes.includes(file.type)) {
        ElMessage.error('只支持 JPG、PNG 格式的图片')
        return
      }

      if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过 5MB')
        return
      }

      console.log('文件验证通过，开始上传...') // 调试信息
      await uploadToQiniu(file)
    }

    // 上传到七牛云
    const uploadToQiniu = async (file) => {
      // 检查token是否存在
      if (!token.value) {
        ElMessage.error('上传token未获取，请刷新页面重试')
        return
      }
      
      console.log('准备上传文件，token:', token.value) // 调试信息
      
             try {
         const formData = new FormData()
         formData.append('file', file)
         formData.append('token', token.value)
         
                   // 添加文件名（可选）
          const timestamp = Date.now()
          const randomStr = Math.random().toString(36).substring(2, 15)
          const fileName = `idcard_${timestamp}_${randomStr}${file.name.substring(file.name.lastIndexOf('.'))}`
          formData.append('key', fileName)
        
        // 调试FormData内容
        console.log('FormData内容:')
        for (let [key, value] of formData.entries()) {
          console.log(`${key}:`, value)
        }

                 // 直接使用华北地区(z1)的上传域名，根据错误信息确定这是正确的区域
         const uploadDomain = 'https://upload-z1.qiniup.com/'
        
        console.log('上传到七牛云:', uploadDomain)
        const response = await fetch(uploadDomain, {
          method: 'POST',
          body: formData
        })
        
        console.log('响应状态:', response.status)
        
        if (!response.ok) {
          // 获取错误响应内容
          const errorText = await response.text()
          console.log('上传失败，状态:', response.status, '错误:', errorText)
          throw new Error(`上传失败: ${response.status} - ${errorText}`)
        }

        console.log('七牛云上传响应状态:', response.status)
        console.log('七牛云上传响应头:', response.headers)
        
        // 获取响应文本
        const responseText = await response.text()
        console.log('七牛云上传响应文本:', responseText)
        
        let result
        try {
          result = JSON.parse(responseText)
        } catch (e) {
          console.error('响应不是有效的JSON:', responseText)
          ElMessage.error('上传响应格式错误')
          return
        }
        
        console.log('七牛云上传响应:', result)
        
                 if (result.key) {
                       // 直接使用HTTP域名，避免SSL证书问题
            const imageUrl = `http://t1cfb88a9.hb-bkt.clouddn.com/${result.key}`
           
           // 设置图片地址
           imgurl.value = imageUrl
           backupDomains.value = [] // 清空备用域名，不再需要
           currentDomainIndex.value = 0
           console.log('上传成功，图片地址:', imgurl.value)
           ElMessage.success('图片上传成功')
          
          // 自动识别身份证
          await recognizeIdCard()
        } else {
          console.error('七牛云上传失败:', result)
          ElMessage.error(result.error || '图片上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('图片上传失败')
      }
    }

     // 处理图片加载错误
     const handleImageError = () => {
       console.log('图片加载失败')
       ElMessage.error('图片加载失败，请重新上传')
     }
     
     // 处理图片加载成功
     const handleImageLoad = () => {
       console.log('图片加载成功')
     }
     
    // 识别身份证
    const recognizeIdCard = async () => {
      if (!imgurl.value) {
        ElMessage.warning('请先上传身份证图片')
        return
      }

      recognizing.value = true
      processingStatus.value = '正在提交识别任务...'
      
      try {
        const response = await authAPI.recognizeIdCard(imgurl.value)
        console.log('身份证识别响应:', response) // 调试信息
        
        // 直接使用axios时，response是完整的axios响应对象
        if (response && response.data && response.data.code === 200) {
          processingStatus.value = '任务已提交，正在处理中...'
          ElMessage.success('识别任务已提交')
          
          // 开始定时查询处理结果
          startCheckingResult()
        } else {
          processingStatus.value = ''
          ElMessage.error(response?.data?.message || '识别失败')
          recognizing.value = false
        }
      } catch (error) {
        console.error('识别失败:', error)
        processingStatus.value = ''
        ElMessage.error('身份证识别失败')
        recognizing.value = false
      }
    }

    // 开始定时查询处理结果
    const startCheckingResult = () => {
      // 清除之前的定时器
      if (checkInterval.value) {
        clearInterval(checkInterval.value)
      }
      
      // 设置定时器，每2秒查询一次
      checkInterval.value = setInterval(async () => {
        await checkProcessingResult()
      }, 2000)
    }

    // 查询处理结果
    const checkProcessingResult = async () => {
      try {
        const response = await authAPI.checkIdCardResult(imgurl.value)
        console.log('查询处理结果响应:', response)
        
        if (response && response.data) {
          const { code, data, message } = response.data
          
          if (code === 200 && data) {
            // 处理完成，获取到结果
            // 根据百度API返回格式，data包含success、name、idcard字段
            if (data.success) {
              name.value = data.name || ''
              idcode.value = data.idcard || ''
              processingStatus.value = ''
              recognizing.value = false
              
              // 清除定时器
              if (checkInterval.value) {
                clearInterval(checkInterval.value)
                checkInterval.value = null
              }
              
              ElMessage.success('身份证识别成功')
            } else {
              // 识别失败
              processingStatus.value = data.message || '识别失败'
              recognizing.value = false
              
              // 清除定时器
              if (checkInterval.value) {
                clearInterval(checkInterval.value)
                checkInterval.value = null
              }
              
              ElMessage.error(data.message || '身份证识别失败')
            }
          } else if (code === 202) {
            // 仍在处理中
            processingStatus.value = message || '正在处理中...'
          } else {
            // 其他状态
            processingStatus.value = message || '处理状态未知'
          }
        }
      } catch (error) {
        console.error('查询处理结果失败:', error)
        // 不显示错误消息，继续查询
      }
    }

    // 停止定时器
    const stopChecking = () => {
      if (checkInterval.value) {
        clearInterval(checkInterval.value)
        checkInterval.value = null
      }
    }

    // 重新上传
    const reupload = () => {
      // 停止定时器
      stopChecking()
      
      imgurl.value = ''
      name.value = ''
      idcode.value = ''
      processingStatus.value = ''
      recognizing.value = false
      
      if (fileInput.value) {
        fileInput.value.value = ''
      }
    }

    // 提交认证
    const submitVerification = async () => {
      if (!name.value || !idcode.value) {
        ElMessage.warning('请先识别身份证信息')
        return
      }

             submitting.value = true
       try {
         const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
         console.log('用户信息:', userInfo) // 调试信息
         
         const submitData = {
           userid: userInfo.user_id,
           name: name.value,
           idcard: idcode.value,  // 修改参数名从idcode改为idcard
           image_url: imgurl.value
         }
         console.log('提交数据:', submitData) // 调试信息
         
         const response = await authAPI.submitIdCardVerification(submitData)

        console.log('提交认证响应:', response) // 调试信息

        // 直接使用axios时，response是完整的axios响应对象
        if (response && response.data && response.data.success) {
          ElMessage.success('实名认证成功！')
          // 更新本地用户信息
          if (userInfo) {
            userInfo.verify = '1'
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
          }
          
          // 延迟1秒后跳转到home页面，让用户看到成功消息
          setTimeout(() => {
            router.push('/')
          }, 1000)
        } else {
          ElMessage.error(response?.data?.message || '提交失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交认证失败')
      } finally {
        submitting.value = false
      }
    }

    // 页面加载时获取token
    onMounted(() => {
      getQiniuToken()
    })

    // 页面卸载时清理定时器
    onUnmounted(() => {
      stopChecking()
    })

         return {
       token,
       imgurl,
       name,
       idcode,
       recognizing,
       submitting,
       fileInput,
       processingStatus, // 添加处理状态
       backupDomains,
       currentDomainIndex,
       triggerUpload,
       handleFileChange,
       reupload,
       recognizeIdCard,
       submitVerification,
       handleImageError,
       handleImageLoad
     }
  }
}
</script>

<style scoped>
.idcard-verification {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.verification-container {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 100%;
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
}

.image-preview {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.image-actions {
  margin-top: 16px;
}

.result-section {
  border-top: 1px solid #ebeef5;
  padding-top: 30px;
}

.result-section h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 18px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 30px;
}

.loading-section {
  text-align: center;
  padding: 40px;
}

 .loading-section p {
   margin-top: 16px;
   color: #606266;
 }

 .loading-spinner {
   width: 40px;
   height: 40px;
   border: 4px solid #f3f3f3;
   border-top: 4px solid #409eff;
   border-radius: 50%;
   animation: spin 1s linear infinite;
   margin: 0 auto 16px;
 }

 @keyframes spin {
   0% { transform: rotate(0deg); }
   100% { transform: rotate(360deg); }
 }

/* 响应式设计 */
@media (max-width: 768px) {
  .verification-container {
    margin: 10px;
    padding: 20px;
  }
  
  .upload-area {
    padding: 30px 20px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>
